package com.dapeis.api.controller.collocation.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.SysTipsException;
import com.ag.module.common.api.domain.SMS;
import com.ag.module.common.api.service.SMSService;
import com.ag.module.common.api.service.text.base.DicText;
import com.ag.utils.NumberUtils;
import com.dapeis.api.controller.ISMSController;
import com.dapeis.api.controller.RestController;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.exception.SMSSendFaildException;
import com.dapeis.tx.sms.SMSNoticeText;
import com.google.gson.JsonElement;

@Controller
@RequestMapping("/dps/sms")
public class SMSControllerImpl extends RestController implements
	ISMSController {

    @Resource
    SMSService smsService;

    @Override
    public JsonElement send(@PathVariable String sendChannel, String contact,
	    HttpServletRequest request) {
	if (StringUtils.isBlank(sendChannel) || StringUtils.isBlank(contact)) {
	    throw new InvalidParamException();
	}
	if (!contact.matches(StylistConstants.mobilePhonePattern.pattern())
		|| contact.length() != 11) {
	    throw new InvalidParamException("手机号码格式不正确");
	}

	String verifyCode = String.valueOf(NumberUtils.random(4));
	int channelType = -1;
	DicText nt = null;
	if ("login".equals(sendChannel)) {
	    channelType = StylistConstants.ChannelType.DPS.APP_LOGIN;
	    nt = new SMSNoticeText(verifyCode);
	}else{
	    throw new SysTipsException("非法发送短信渠道!");
	}
	SMS unExpireationTimeSMS = smsService.getUnExpireationTimeSMS(
		channelType, contact);
	if (unExpireationTimeSMS != null) {// 如果有,
	    smsService.getDefaultSMSSendChannel().sendSMS(contact,
		    unExpireationTimeSMS.getContent());
	} else {
	    boolean flag = smsService.sendSMS(channelType, contact, verifyCode,
		    nt.content());
	    if (!flag) {
		throw new SMSSendFaildException();
	    }
	}
	
	return buildSuccess();
    }
    

}
